package com.net.xpay.web.secutiry;

import com.net.common.model.Result;
import com.net.xpay.core.constant.PoseidonErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
  on 01/02/2018.
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    private SecurityHelper securityHelper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        if (exception == null) {
            securityHelper.sendRestResult(response, new Result(PoseidonErrorCode.BUSINESS_ERROR, "登陆失败"));
            return;
        }
        if (WebAuthenticationException.class.isAssignableFrom(exception.getClass())) {
            WebAuthenticationException e = (WebAuthenticationException) exception;
            securityHelper.removeInvalidSessionCookie(request, response);
            securityHelper.sendRestResult(response, new Result(e.getErrorCode(), e.getErrorMessage()));
        }
    }
}
